package com.exceptions;

import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class CustomExtHandler {

    /**
     * 捕获全局异常,处理所有不可知的异常
     */
    @ExceptionHandler(value=Exception.class)
    Object handleException(Exception e,HttpServletRequest request){
        e.printStackTrace();
        Map<String, Object> map = new HashMap<>();
        map.put("code", -1);
        map.put("msg", JSONObject.toJSONString(e.getStackTrace()));
        map.put("url", request.getRequestURL());
        return map;
    }

    /**
     * 功能描述: 处理自定义异常类
     */
    @ExceptionHandler(value = ApiException.class)
    Object handleMyException(ApiException e, HttpServletRequest request){
        //f返回json数据
        Map<String, Object> map = new HashMap<>();
        map.put("code", e.getCode());
        map.put("msg", e.getMsg());
        map.put("url", request.getRequestURL());
        return map;
    }
}